#include<iostream>
#include<cstring>
using namespace std;
const int N = 910, M = 2 * N;
int h[N], e[M], ne[M], idx; 
int f[N][20];
int d[N];
int dis[N];
int n, m;
void add(int a, int b)
{
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u, int fa)
{
	for (int i = h[u]; ~i; i = ne[i]) {
		int j = e[i];
		if (j != fa) {
			dis[j] = dis[u] + 1;
			f[j][0] = u;
			for (int k = 1; (1 << k) <= dis[j]; k++) {
				f[j][k] = f[f[j][k - 1]][k - 1];
			}
			dfs(j, u);
		}
	}
}

int lca(int a, int b)
{
	if (dis[a] < dis[b])swap(a, b);
	int d = dis[a] - dis[b];
	//d==5
	//101
	for (int i = 0; d; i++) {
		if (d & 1)a = f[a][i];
		d /= 2;
	}
	if (a == b)return a;
	for (int i = 18; i >= 0; i--) {
		if (f[a][i] != f[b][i]) {
			a = f[a][i], b = f[b][i];
		}
	}
	return f[a][0];
}
int main()
{
	cin >> n;
	memset(h, -1, sizeof(h));
	for (int i = 0; i < n; i++) {
		int x;
		cin >> x;
		int y;
		cin >> y;
		while (y--) {
			int z;
			cin >> z;
			add(x, z);
			add(z, x);
			d[z]++;
		}
	}
	int root = 0;
	for (int i = 1; i <= n; i++) {
		if (!d[i]) {
			root = i;
			break;
		}
	}
	//cout << "root==" << root << endl;
	dis[root] = 1;
	dfs(root, 0);
	/*for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= 18; j++) {
			if (dis[f[i][j - 1]] >= 1) {
				f[i][j] = f[f[i][j - 1]][j - 1];
			}
			else break;
		}
	}*/
	/*for (int i = 1; i <= n; i++) {
		for (int j = 1; (1 << j) <= dis[i]; j++) {
			f[i][j] = f[f[i][j - 1]][j - 1];
		}
	}*/
	//cout <<"=="<< f[3][0] << "  " << f[3][1] << endl;
    cin >> m;
	while (m--) {
		int a, b;
		cin >> a >> b;
		cout << a << " " << b << " = " << lca(a, b) << endl;
	}
	return 0;
}